#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>

static int init(void)
{
    key_t key;
    int sem_id;

    key = ftok(".", 's');
    sem_id = semget(key, 2, IPC_CREAT | 0755);

    return sem_id;
}

int main(void)
{
    struct sembuf sops[2];
    int sem_id;

    sops[0].sem_num = 0;
    sops[0].sem_op = -1;
    sops[0].sem_flg = 0;

    sops[1].sem_num = 1;
    sops[1].sem_op = 1;
    sops[1].sem_flg = 0;

    sem_id = init();
    printf("this is consumer\n");

    while (1) {
        printf("before consumer:\n");
        printf("productor number is %d\n", semctl(sem_id, 0, GETVAL));
        printf("space number is %d\n", semctl(sem_id, 1, GETVAL));

        semop(sem_id, (struct sembuf *)&sops[0], 1);
        printf("now consumering......\n");
        semop(sem_id, (struct sembuf *)&sops[1], 1);

        printf("after consumer\n");
        printf("space number is %d\n", semctl(sem_id, 1, GETVAL));
        printf("productor number is %d\n\n", semctl(sem_id, 0, GETVAL));
        sleep(4);
    }
}